package com.it.schoolhomeos.controller;

import com.it.schoolhomeos.entity.User;
import com.it.schoolhomeos.enums.Role;
import com.it.schoolhomeos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
@Tag(name = "家长管理", description = "提供家长用户的管理功能")
public class ParentController {

    @Autowired
    private UserService userService;

    @GetMapping("/parents/init")
    @Operation(summary = "初始化测试数据", description = "创建一个测试家长用户")
    public ResponseEntity<Map<String, Object>> initTestData() {
        try {
            // 检查是否已存在
            if (userService.existsByUsername("parent1")) {
                return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "message", "测试家长用户已存在",
                    "username", "parent1",
                    "password", "123456"
                ));
            }
            
            // 创建测试家长用户
            User parent = new User();
            parent.setUsername("parent1");
            parent.setPassword("123456"); // 会在service中加密
            parent.setName("测试家长");
            parent.setPhone("13800138001");
            parent.setEmail("parent1@example.com");
            parent.setRole(Role.PARENT);
            parent.setEnabled(true);
            parent.setCreateTime(LocalDateTime.now());
            parent.setUpdateTime(LocalDateTime.now());
            
            User savedParent = userService.createParent(parent);
            
            Map<String, Object> result = new HashMap<>();
            result.put("status", "success");
            result.put("message", "测试家长用户创建成功");
            result.put("username", savedParent.getUsername());
            result.put("password", "123456"); // 原始密码
            result.put("id", savedParent.getId());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                "status", "error",
                "message", "创建测试家长用户失败: " + e.getMessage()
            ));
        }
    }

    @GetMapping("/parents")
    @Operation(summary = "获取家长列表", description = "分页获取所有家长用户")
    public ResponseEntity<Page<User>> getParents(
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        return ResponseEntity.ok(userService.findParents(page, size, keyword));
    }

    @GetMapping("/parents/{id}")
    @Operation(summary = "获取家长详情", description = "根据ID获取家长用户详情")
    public ResponseEntity<User> getParent(@Parameter(description = "家长ID") @PathVariable Long id) {
        return ResponseEntity.ok(userService.findParentById(id));
    }

    @PostMapping("/parents")
    @Operation(summary = "创建家长", description = "创建新的家长用户")
    public ResponseEntity<User> createParent(@Parameter(description = "家长信息") @RequestBody User user) {
        return ResponseEntity.ok(userService.createParent(user));
    }

    @PutMapping("/parents/{id}")
    @Operation(summary = "更新家长", description = "更新家长用户信息")
    public ResponseEntity<User> updateParent(
            @Parameter(description = "家长ID") @PathVariable Long id,
            @Parameter(description = "家长信息") @RequestBody User user) {
        user.setId(id);
        return ResponseEntity.ok(userService.updateParent(user));
    }

    @DeleteMapping("/parents/{id}")
    @Operation(summary = "删除家长", description = "删除指定的家长用户")
    public ResponseEntity<Void> deleteParent(@Parameter(description = "家长ID") @PathVariable Long id) {
        userService.deleteParent(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/parents/list")
    @Operation(summary = "获取所有家长列表", description = "获取所有家长的简化信息，用于下拉选择")
    public ResponseEntity<Map<String, Object>> getAllParents() {
        List<User> parents = userService.findAllParents();
        List<Map<String, Object>> simplifiedParents = parents.stream()
                .map(parent -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", parent.getId());
                    map.put("name", parent.getName());
                    map.put("username", parent.getUsername());
                    map.put("phone", parent.getPhone());
                    return map;
                })
                .collect(Collectors.toList());

        Map<String, Object> response = new HashMap<>();
        response.put("status", "success");
        response.put("message", "获取家长列表成功");
        response.put("data", simplifiedParents);
        
        return ResponseEntity.ok(response);
    }
} 